## Version derivada desde iscam
## jc quiroz

rm(list=ls())

require(hacks)	#transparent colors using the function colr("color",tranparency)
require(Hmisc)
source("read.admb.R")

# Graphics defaults.
.VIEWCEX    <- 1            # Generic default cex for axis labels etc.
.VIEWPANCEX <- 1            # Default cex for panLab.

.VIEWMAR  <- c(3, 3, 1, 1)  # Multi-panel plots: plot margin sizes c(b,l,t,r).
.VIEWOMA  <- c(2, 2, 1, 1)  # Multi-panel plots: outer margin sizes c(b,l,t,r).
.VIEWLAS  <- 1

.REPFILES <- list.files(pattern="\\.rep")
.VIEWTRCK <- "path_out.txt"  # File containing list of report files.
.TABLEDIR <- "xxx/tables/"


verOut	<- function()
{
	.despliegaX11("mosard")
}


.despliegaX11 <- function(win)
{
	#Required libraries
	require(PBSmodelling)
        require(lattice)
        require(date)
		
	#Close any open graphics devices
	graphics.off()
	closeWin()
	
	#Create a file list object for selection
	tmp <- read.table( file = .VIEWTRCK,  as.is=TRUE,  header=TRUE,  sep="," )
	cat( "Lectura desde ruta:",.VIEWTRCK, "realizada.\n" )
	ifiles <- tmp

	#Create new window based on iscamWin.txt
	createWin("mosardx11.txt")
	
	#Default Graphic directory
	wdir = paste(getwd(), sep="")
	setWinVal(list(graphicDirectory=wdir))
	
}


.arrancaPlot <- function()
  {
    	guiInfo <- getWinVal(scope="L")
	guiChanges <- list()
        hdr <- ifiles

        if ( autoLayout )
          {
            winCols <- 1
            winRows <- 1
          }
	
	newPlot <- TRUE
	if ( !autoLayout )
          {
            winCols <- ncols
            winRows <- nrows
            newPlot <- FALSE
	    mfg <- par( "mfg" )
	    if ( (mfg[1]==mfg[3]) && (mfg[2]==mfg[4]) )
	      newPlot <- TRUE
          }

	## Update the gui
	guiChanges$ncols = winCols
	guiChanges$nrows = winRows
	setWinVal( guiChanges )

        ## set graphical parameters
	#if (newPlot)
        #  {
        #    if ( plotbyrow )
        #      par( oma=.VIEWOMA, mar=.VIEWMAR, mfrow=c(winRows,winCols) )
        #    else
        #      par( oma=.VIEWOMA, mar=.VIEWMAR, mfcol=c(winRows,winCols) )
        #  }

        repObj <- read.admb(ifiles$Control.File)
        mcfile <- paste(ifiles$Control.File,".mcmc", sep="")
		if(file.exists(mcfile))
			repObj$mcmc = read.table( mcfile, header=TRUE )
		else
			cat("NB. MCMC file missing. \n")

        julianD <- mdy.date(repObj$mes, 1, 1994 + repObj$year)
        DateJ <- date.mdy(julianD)
        repObj$DJ <- DateJ
        
      if ( plotType=="CPUE" )
          {
            .plotCPUE( repObj, guiInfo)
          }
        
        if ( plotType=="Captura" )
          {
            .plotCatch( repObj, guiInfo)
          }

        if ( plotType=="Cruceros" )
          {
            .plotSurvey( repObj, guiInfo)
          }
        
        if ( plotType=="Com.Reclas" )
          {
            .plotCLReclas( repObj, guiInfo)
          }
        
        if ( plotType=="Com.Pelaces" )
          {
            .plotCLPelaces( repObj, guiInfo)
          }
        
        if ( plotType=="Selectividad" )
          {
            .plotSelectividad( repObj, guiInfo)
          }
        
        if ( plotType=="SeasonF" )
          {
            .plotSeasonF( repObj, guiInfo)
          }

      
        if (savePDF)
          {
		setWinVal(c(figFileName=plotType))
		.saveGraphic()
          }
        
  }


.plotCPUE <- function( repObj, guiInfo)
  {
    with(repObj,
         {g <- xyplot(pCPUE + obs_CPUE ~ DJ$month[yrsCPUE]
                      | factor(DJ$year[yrsCPUE]),
                      lty = 1, col = c("black","red"), 
                      ylab = "Captura [ton]", xlab = 'Mes',
                      main = paste('Ajuste', guiInfo$plotType, guiInfo$ifiles$Stock, sep = ' '),
                 type = c("l","p"), distribute.type = TRUE)
          print(g)
         })
         
  }


.plotCatch <- function( repObj, guiInfo)
  {
    with(repObj,
         {g <- xyplot(pCatch/1000 + Obs_catch/1000 ~ mes | factor(year+1994),
                 lty = 1, col = c("black","red"),
                 ylab = "Captura [ton]",  xlab = 'Mes',
                 main = paste('Ajuste',guiInfo$plotType, guiInfo$ifiles$Stock, sep = ' '),
                 type = c("l","p"), distribute.type = TRUE)
          print(g)
         })
         
  }

.plotSurvey <- function( repObj, guiInfo)
  {
    #par(mfrow=c(1, 2), oma=c(0, 0, 4, 0))
    par(mfrow=c(1,2))
    with(repObj,
         {
          plot(repObj$DJ$year[repObj$yrsReclas],obs_Reclas/1e3,
               type='p',col='red',ylab = 'Biomasa [mil*ton]', xlab = 'Año',
               main = paste(guiInfo$plotType,"Reclas",sep=" "))
          lines(DJ$year[yrsReclas],Index_Reclas/1e3, type = 'l')
          plot(DJ$year[yrsPelaces],obs_Pelaces/1e3,
               type='p',col='red', ylab = 'Biomasa [mil*ton]', xlab = 'Año',
               main = paste(guiInfo$plotType,"Pelaces",sep=" "))
          lines(DJ$year[yrsPelaces],Index_Pelaces/1e3, type = "l")
        })
  }
          

.plotCLReclas <- function( repObj, guiInfo)
  {
    with(repObj,
         {
           w1 <- data.frame(repObj$pCLReclas)
           w2 <- data.frame(repObj$obsCLReclas)
           colnames(w1) <- colnames(w2) <- c(seq(3,33,1))
           rownames(w1) <- rownames(w2) <- repObj$DJ$year[repObj$yrsCLReclas]
           reclas.p <- stack(w1)
           reclas.p[,3] <- repObj$DJ$year[repObj$yrsCLReclas]
           reclas.p[,4] <- 1
           reclas.o <- stack(w2)
           reclas.o[,3] <- repObj$DJ$year[repObj$yrsCLReclas]
           reclas.o[,4] <- 2

           reclas <- rbind(reclas.p,reclas.o)
           colnames(reclas) <- c('prop','length','year','fit')
           reclas$length <- as.numeric(as.character(reclas$length))
           reclas$year <- ordered(reclas$year)
           reclas$fit <- ordered(reclas$fit)

           g <- xyplot(prop ~ length | year, groups=reclas$fit, data=reclas,
                  auto.key=list(columns=2,text=c("Modelo", "Observación"),
                    lines=T, points=T, rectangles=F, lwd=1, cex =1.2),
                  par.settings=simpleTheme(col=c('black', 'steelblue'),
                    pch=c(20, 17)), type="b", xlab="Talla", ylab="Proporción a la Talla",
                       main = paste("Ajustes",guiInfo$plotType,sep=" "),
                  lty=1, cex.lab=1.3, cex.axis=1, as.table=TRUE,
                  scales=list(x=list(rot=0, cex=0.6)))

          print(g)
         })
  }
          

.plotCLPelaces <- function( repObj, guiInfo)
  {
    with(repObj,
         {
           w1 <- data.frame(pCLPelaces)
           w2 <- data.frame(obsCLPelaces)
           colnames(w1) <- colnames(w2) <- c(seq(3,33,1))
           rownames(w1) <- rownames(w2) <- DJ$year[yrsCLPelaces]
           pelaces.p <- stack(w1)
           pelaces.p[,3] <- DJ$year[yrsCLPelaces]
           pelaces.p[,4] <- 1
           pelaces.o <- stack(w2)
           pelaces.o[,3] <- DJ$year[yrsCLPelaces]
           pelaces.o[,4] <- 2

           pelaces <- rbind(pelaces.p,pelaces.o)
           colnames(pelaces) <- c('prop','length','year','fit')
           pelaces$length <- as.numeric(as.character(pelaces$length))
           pelaces$year <- ordered(pelaces$year)
           pelaces$fit <- ordered(pelaces$fit)

           g <- xyplot(prop ~ length | year, groups=pelaces$fit, data=pelaces,
                  auto.key=list(columns=2,text=c("Modelo", "Observación"),
                    lines=T, points=T, rectangles=F, lwd=1, cex =1.2),
                  par.settings=simpleTheme(col=c('black', 'steelblue'),
                    pch=c(20, 17)), type="b", xlab="Talla", ylab="Proporción a la Talla", 
                 main = paste("Ajustes",guiInfo$plotType,sep=" "),
                  lty=1, cex.lab=1.3, cex.axis=1, as.table=TRUE,
                  scales=list(x=list(rot=0, cex=0.6)))

          print(g)
         })
  }


.plotSelectividad <- function(repObj, guiInfo)
  {
    #par(mfrow=c(1, 2), oma=c(0, 0, 4, 0))
    par(mfrow=c(2,2))
    with(repObj,
         {
          plot(seq(1,48,1),selFishery,
               type='l',col='red',ylab = 'Selectividad [proporcion]',
               xlab = 'Edad [meses]', xlim=c(1,20),
               main = paste(guiInfo$plotType,"Pesquería",sep=" "))
          lines(seq(1,48,1),maturity,type='l',lty=2,col=3)
          legend(10,0.8,c('Ojiva','Madurez'),lty=c(1,2),
                 col=c('red',3), box.lwd=0)
          
          plot(seq(1,48,1),selReclas,
               type='l',col='red',ylab = 'Selectividad [proporcion]',
               xlab = 'Edad [meses]', xlim=c(1,20),
               main = paste(guiInfo$plotType,"Reclas",sep=" "))
          lines(seq(1,48,1),maturity,type='l',lty=2,col=3)
          
          plot(seq(1,48,1),selPelaces,
               type='l',col='red',ylab = 'Selectividad [proporcion]',
               xlab = 'Edad [meses]', xlim=c(1,20),
               main = paste(guiInfo$plotType,"Pelaces",sep=" "))
          lines(seq(1,48,1),maturity,type='l',lty=2,col=3)

           plot(seq(1,48,1),selFishery,
               type='l',lty=1, col=1, ylab = 'Selectividad [proporcion]',
               xlab = 'Edad [meses]', xlim=c(1,20),
               main = paste(guiInfo$plotType,"Todas",sep=" "))
          lines(seq(1,48,1),selReclas,lty=2,col=2)
          lines(seq(1,48,1),selPelaces,lty=3,col=4)
          legend(10,0.8, c("Pesquería","Reclas","Pelaces"),
                 col=c(1,2,4), lty=1:3, box.lwd=0)
        })
  }
         

.plotSeasonF <- function(repObj, guiInfo)
  {
	with(repObj, {
		par(mgp=c(3, 3, 5))
		plot.sel<-function(x, y, z, ...)
		{
			#z <- z/max(z)
			z0 <- 0#min(z) - 20
			z <- rbind(z0, cbind(z0, z, z0), z0)
			x <- c(min(x) - 1e-10, x, max(x) + 1e-10)
			y <- c(min(y) - 1e-10, y, max(y) + 1e-10)
			clr=colorRampPalette(c('honeydew','orange','lawngreen'),space='Lab')
                                        #(c("honeydew","lawngreen"))
			nbcol = 30
			iclr=clr(nbcol)
			nrz <- nrow(z)
			ncz <- ncol(z)
			zfacet <- z[-1, -1]+z[-1, -ncz]+z[-nrz, -1]+z[-nrz, -ncz]
			facetcol <- cut(zfacet, nbcol)
			fill <- matrix(iclr[facetcol],nr=nrow(z)-1,nc=ncol(z)-1)
			fill[ , i2 <- c(1,ncol(fill))] <- "white"
			fill[i1 <- c(1,nrow(fill)) , ] <- "white"

			par(bg = "transparent")
			persp(x, y, z, theta = 35, phi = 25, col = fill, expand=5, 
				shade=0.65, ltheta=45 , scale = FALSE, axes = TRUE, d=3,  
				xlab="Año",ylab="Mes",zlab="Mortalidad [relativa]", 
				ticktype="detailed",...)
                      }
		plot.sel(sort(as.numeric(unique(repObj$DJ$year))),
                         sort(as.numeric(unique(repObj$DJ$month))), seasonF, 
			main=paste('Estacionalidad de F en',guiInfo$ifiles$Stock,sep=''))
              })
  }


.saveGraphic <- function()
  {

	guiInfo <- getWinVal(scope="L")
	
	if(graphicDirectory=="Working Directory")
		graphicDirectory = getwd()
	if(figFileName=="Figure File Name")
	{
		figFileName = plotType
		setWinVal(c(figFileName=plotType))
	}
	figFile = figFileName
	
	fileName = paste(graphicDirectory, "/escape_fig_", figFile,".pdf", sep="")
	dev.copy2pdf(file=fileName)
	cat("Gráfico guardado como: ", fileName, "\n")
  }
